﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using DatabaseComponent;
using Shohdi.DataHandler;

public partial class QuestionsViewEN : System.Web.UI.Page
{

    protected int numberOfAnswersReaded = 0;
    protected int numberOfIsAnsweredReaded = 0;
    List<QuestionsAnswers> lstQuestionsAnswersReaded = new List<QuestionsAnswers>();


    public List<Questions> lstQuestionsGrid
    {
        get
        {
            if (ViewState["lstQuestionsGrid"] == null)
            {
                ViewState["lstQuestionsGrid"] = System.Guid.NewGuid().ToString();
            }


            if (Session[ViewState["lstQuestionsGrid"].ToString()] == null)
            {
                Session[ViewState["lstQuestionsGrid"].ToString()] = new List<Questions>();

            }

            return (List<Questions>)Session[ViewState["lstQuestionsGrid"].ToString()];

        }
        set
        {
            if (ViewState["lstQuestionsGrid"] == null)
            {
                ViewState["lstQuestionsGrid"] = System.Guid.NewGuid().ToString();
            }

            Session[ViewState["lstQuestionsGrid"].ToString()] = value;
        }   
   
   

    }




    long mQuestionsID
    {
        get
        {
            if (ViewState["mQuestionsID"] == null)
            {
                ViewState["mQuestionsID"] = System.Guid.NewGuid().ToString();
            }


            if (Session[ViewState["mQuestionsID"].ToString()] == null)
            {
                long obj = -1;
                Session[ViewState["mQuestionsID"].ToString()] = obj;

            }

            return (long)Session[ViewState["mQuestionsID"].ToString()];

        }
        set
        {
            if (ViewState["mQuestionsID"] == null)
            {
                ViewState["mQuestionsID"] = System.Guid.NewGuid().ToString();
            }

            Session[ViewState["mQuestionsID"].ToString()] = value;
        }
    }


    Questions mObjQuestions
    {
        get
        {
            if (ViewState["mObjQuestions"] == null)
            {
                ViewState["mObjQuestions"] = System.Guid.NewGuid().ToString();
            }


            if (Session[ViewState["mObjQuestions"].ToString()] == null)
            {
                Session[ViewState["mObjQuestions"].ToString()] = new Questions();

            }

            return (Questions)Session[ViewState["mObjQuestions"].ToString()];

        }
        set
        {
            if (ViewState["mObjQuestions"] == null)
            {
                ViewState["mObjQuestions"] = System.Guid.NewGuid().ToString();
            }

            Session[ViewState["mObjQuestions"].ToString()] = value;
        }
    }




   
    public long currentCoursesID
    {
        get
        {
            if (Request["id"] == null)
                Response.Redirect("LoginEN.aspx");
            string guid = Request["id"].ToString();
            if (Session[guid] == null)
                Response.Redirect("LoginEN.aspx");

            long lRet = -1;

            try
            {
                lRet = long.Parse(Session[guid].ToString());
                return lRet;

            }
            catch
            {
                Response.Redirect("LoginEN.aspx");
            }

            return -1;
        }
    }





    protected void Page_Load(object sender, EventArgs e)
    {



        Persons objPersons = GlobalVars.getCurrentPerson();
        checkSecurityAndCustomizePage(objPersons);
       
        if (!Page.IsPostBack)
        {
            bindQuestionTypes();
            bindGrid("");
            editLoad();
        }

        

    }

    /// <summary>
    /// this function will bind all questions types in the drop down list
    /// </summary>
    protected void bindQuestionTypes()
    {

        QuestionTypesDB objQuestionTypesDB = new QuestionTypesDB(ConnectionStrings.LMS);


        List<QuestionTypes> lstQuestionTypes = objQuestionTypesDB.Search(new QuestionTypes());

        ddlQuestionTypesID.DataSource = lstQuestionTypes;
        ddlQuestionTypesID.DataTextField = "QuestionTypeEN";
        ddlQuestionTypesID.DataValueField = "ID";
        ddlQuestionTypesID.DataBind();

        if (ddlQuestionTypesID.SelectedValue == "1")
        {
            pnlChoose.Visible = true;
            pnlRightWrong.Visible = false;

        }
        else
        {
            pnlChoose.Visible = false;
            pnlRightWrong.Visible = true;

        }


    }



    /// <summary>
    /// this function will bind the grid 
    /// </summary>
    protected void bindGrid(string strIn)
    {

        List<Questions> lstQuestions = search(strIn);



        lstQuestionsGrid = lstQuestions;

        grdUsers.DataSource = lstQuestions;
        grdUsers.DataBind();
    }



    /// <summary>
    /// it will check the security and customize the page
    /// </summary>
    /// <param name="currentPerson">the person to set security to his previleges</param>
    protected void checkSecurityAndCustomizePage(Persons currentPerson)
    {
        //Security Check

        if (!currentPerson.lstAllRulesIDs.Contains((long)RulesEnum.Questions_of_courses_page))
            Response.Redirect("LoginEN.aspx");


        if (!currentPerson.lstAllRulesIDs.Contains((long)RulesEnum.Editing_questions_of_courses_page))
        {
            btnSave.Enabled = false;
            btnDelete.Enabled = false;
        }
       




    }
    
    protected void btnSearch_Click(object sender, EventArgs e)
    {

        bindGrid(txtSearch.Text);
       
    }

    /// <summary>
    /// this function will search in questions and return the values
    /// </summary>
    /// <param name="txtText">the text to search for</param>
    /// <returns>a list of questions matched</returns>
    protected List<Questions> search(string txtText)
    {
        long coursesID = currentCoursesID;
        QuestionsDB objQuestionsDB = new QuestionsDB(ConnectionStrings.LMS);
        List<Questions> lstRet = new List<Questions>();
        if (txtText.Trim() == "")
        {
            List<Questions> lstNew = objQuestionsDB.Select(" top 100 ", " where [CoursesID]='" + coursesID + "' order by [QuestionEN] ");
            //lstNew = new List<TicketType>(from objFol in lstNew where objFol.StatusID != 2 select objFol);
            //no status
            return lstNew;
        }

        string[] strValues = null;
        if (txtText.Trim()[0] == '\"' && txtText.Trim()[txtText.Trim().Length - 1] == '\"')
        {
            try
            {
                strValues = new string[] { txtText.Trim().Substring(1, txtText.Trim().Length - 2) };
                if (strValues[0] == "")
                    strValues = new string[0];
            }
            catch
            {
                strValues = new string[0];
            }
        }
        else
        {
            strValues = txtText.Trim().Split(" ".ToCharArray(), StringSplitOptions.RemoveEmptyEntries);
        }

        foreach (string strValue in strValues)
        {
            Questions objQuestions = new Questions();

            string strSearchVal = "'%" + strValue.Replace("'", "''") + "%'";

            string where = " where [CoursesID]='" + coursesID + "' and ([QuestionAR] LIKE " + strSearchVal + " OR [QuestionEN] LIKE " + strSearchVal + " ) order by [QuestionEN] ";

            
            List<Questions> lstQuestions = objQuestionsDB.Select(" top 100 ", where);



            

            //lstTicketType = new List<TicketType>(from objFol in lstTicketType where objFol.StatusID != 2 select objFol);
            //no status
            foreach (Questions objFol in lstQuestions)
            {
                if ((from objIn in lstRet where objIn.ID == objFol.ID select objIn).ToList().Count == 0)
                {
                    lstRet.Add(objFol);
                }
            }

        }


        return lstRet;



    }





    protected void grdUsers_RowDeleting(object sender, GridViewDeleteEventArgs e)
    {

        Persons objCurrentPersons = GlobalVars.getCurrentPerson();
        checkSecurityAndCustomizePage(objCurrentPersons);

        //security check

        if (!objCurrentPersons.lstAllRulesIDs.Contains((long)RulesEnum.Editing_questions_of_courses_page))
        {
            lblError.Text = "Security error , you can view only";
            lblResult.Text = "";

            return;
        }


        long QuestionsID = long.Parse(grdUsers.DataKeys[e.RowIndex]["ID"].ToString());



        QuestionsDB objQuestionsDB = new QuestionsDB(ConnectionStrings.LMS);
        List<Questions> lstQuestions = objQuestionsDB.getQuestionsByID(QuestionsID);




        if (lstQuestions.Count == 0)
        {
            lblError.Text = "No Questions to delete";
            lblResult.Text = "";
            return;
        }





        //if (lstQuestions[0].lstTickets.Count > 0)
        //{
            
        //    lblError.Text = "Error Deleting this type , there is tickets witch uses it";
            
        //    return;
        //}



        List<QuestionsAnswers> lstQuestionsAnswers = lstQuestions[0].lstQuestionsAnswers;

        ClassDataHandler con = new ClassDataHandler(ConnectionStrings.LMS);
        con.OpenTransConnection(System.Data.IsolationLevel.ReadUncommitted);

        try
        {

            for (int i = 0; i < lstQuestionsAnswers.Count; i++)
            {
                QuestionsAnswersDB objQuestionsAnswers = new QuestionsAnswersDB();
                objQuestionsAnswers.Delete(con, lstQuestionsAnswers[i]);
            }


            objQuestionsDB.Delete(con, lstQuestions[0]);

            con.CommitTransConnection();
            
        }
        catch
        {
            con.RollbackTransConnection();
            lblError.Text = "Error deleting questions.";
            return;
        }



        lblResult.Text = "Deleted ok.";
        bindGrid(txtSearch.Text);
        return;



       



    }

    protected void btnNew_Click(object sender, EventArgs e)
    {
        clearAllControls();
    }
    protected void grdUsers_PageIndexChanging(object sender, GridViewPageEventArgs e)
    {
        grdUsers.DataSource = lstQuestionsGrid;
        grdUsers.PageIndex = e.NewPageIndex;

        grdUsers.DataBind(); 
    }


    /// <summary>
    /// this function will check mQuestionsID to detect update or insert
    /// </summary>
    protected void checkID()
    {
        if (mQuestionsID != -1)
        {
            try
            {

                QuestionsDB objQuestionsDB = new QuestionsDB(ConnectionStrings.LMS);
                List<Questions> lstQuestions = objQuestionsDB.getQuestionsByID(mQuestionsID);
                if (lstQuestions.Count > 0)
                {


                    mObjQuestions = lstQuestions[0];
                    btnDelete.Visible = true;

                }
                else
                {
                    mQuestionsID = ((long)-1);
                    
                }


            }
            catch
            {
                mQuestionsID = ((long)-1);
            }


            
        }
        else
        {
            btnDelete.Visible = false;

        }
    }



    /// <summary>
    /// this will bind the question to update or delete
    /// </summary>
    protected void BindAllControls()
    {
        if (mQuestionsID != -1)
        {

            txtQuestionEN.Text = mObjQuestions.QuestionEN;
            txtQuestionAR.Text = mObjQuestions.QuestionAR;
            ddlQuestionTypesID.SelectedValue = mObjQuestions.QuestionTypesID.ToString();
            ddlQuestionTypesID_SelectedIndexChanged(this, new EventArgs());
            txtQuestionDegree.Text = mObjQuestions.QuestionDegree.ToString();

            if (mObjQuestions.QuestionTypesID == 1)
            {
                txtAnswera.Text = "";
                txtAnsweraEN.Text = "";
                chkAnswera.Checked = false;
                txtAnswerb.Text = "";
                txtAnswerbEN.Text = "";
                chkAnswerb.Checked = false;
                txtAnswerc.Text = "";
                txtAnswercEN.Text = "";
                chkAnswerc.Checked = false;
                txtAnswerd.Text = "";
                txtAnswerdEN.Text = "";
                chkAnswerd.Checked = false;

                try
                {
                    txtAnswera.Text = mObjQuestions.lstQuestionsAnswers[0].AnswerAR;
                    txtAnsweraEN.Text = mObjQuestions.lstQuestionsAnswers[0].AnswerEN;
                    chkAnswera.Checked = mObjQuestions.lstQuestionsAnswers[0].IsAnswer;

                    txtAnswerb.Text = mObjQuestions.lstQuestionsAnswers[1].AnswerAR;
                    txtAnswerbEN.Text = mObjQuestions.lstQuestionsAnswers[1].AnswerEN;
                    chkAnswerb.Checked = mObjQuestions.lstQuestionsAnswers[1].IsAnswer;


                    txtAnswerc.Text = mObjQuestions.lstQuestionsAnswers[2].AnswerAR;
                    txtAnswercEN.Text = mObjQuestions.lstQuestionsAnswers[2].AnswerEN;
                    chkAnswerc.Checked = mObjQuestions.lstQuestionsAnswers[2].IsAnswer;


                    txtAnswerd.Text = mObjQuestions.lstQuestionsAnswers[3].AnswerAR;
                    txtAnswerdEN.Text = mObjQuestions.lstQuestionsAnswers[3].AnswerEN;
                    chkAnswerd.Checked = mObjQuestions.lstQuestionsAnswers[3].IsAnswer;

                }
                catch
                {

                }
               
            }
            else
            {

                try
                {
                    if (mObjQuestions.lstQuestionsAnswers[1].IsAnswer)
                    {
                        rblChooseAnswer.SelectedValue = "1";

                    }
                    else
                        rblChooseAnswer.SelectedValue = "0";

                }
                catch
                {
                }


            }

        }
    }


    /// <summary>
    /// this function will get the answer from controls
    /// </summary>
    /// <param name="txtAR">the arabic text</param>
    /// <param name="txtEN">the english text</param>
    /// <param name="cb">the checkbox is answered or not</param>
    /// <returns>a question answer or null</returns>
    protected QuestionsAnswers getQuestionsAnswers(TextBox txtAR, TextBox txtEN, CheckBox cb)
    {
        if (txtAR.Text.Trim() != "" || txtEN.Text.Trim() != "")
        {
            numberOfAnswersReaded++;
            QuestionsAnswers qa = new QuestionsAnswers();
            

            qa.AnswerAR = txtAR.Text.Trim() == ""?txtEN.Text:txtAR.Text;
            qa.AnswerEN = txtEN.Text.Trim() == ""?txtAR.Text:txtEN.Text;
            
            if (cb.Checked)
            {
                numberOfIsAnsweredReaded++;
            }
            qa.IsAnswer = cb.Checked;

            return qa;

        }
        else
        {
            return null;
        }

    }


    /// <summary>
    /// this function will read all controls values
    /// </summary>
    protected void ReadAllControls()
    {
        mObjQuestions.CoursesID = currentCoursesID;
        mObjQuestions.QuestionEN = txtQuestionEN.Text;
        mObjQuestions.QuestionAR = txtQuestionAR.Text;
        mObjQuestions.QuestionTypesID = long.Parse(ddlQuestionTypesID.SelectedValue);

        
        mObjQuestions.QuestionDegree = Double.Parse(txtQuestionDegree.Text) ;


        if (ddlQuestionTypesID.SelectedValue == "1")
        {
            lstQuestionsAnswersReaded.Clear();
            QuestionsAnswers qa = new QuestionsAnswers();

            qa = getQuestionsAnswers(txtAnswera, txtAnsweraEN, chkAnswera);
            if (qa != null)
                lstQuestionsAnswersReaded.Add(qa);
            qa = getQuestionsAnswers(txtAnswerb, txtAnswerbEN, chkAnswerb);
            if (qa != null)
                lstQuestionsAnswersReaded.Add(qa);

            qa = getQuestionsAnswers(txtAnswerc, txtAnswercEN, chkAnswerc);
            if (qa != null)
                lstQuestionsAnswersReaded.Add(qa);


            qa = getQuestionsAnswers(txtAnswerd, txtAnswerdEN, chkAnswerd);
            if (qa != null)
                lstQuestionsAnswersReaded.Add(qa);

        }
        else
        {
            lstQuestionsAnswersReaded.Clear();
            numberOfAnswersReaded++;

            QuestionsAnswers qa = new QuestionsAnswers();
            qa.AnswerAR = "عبارة خاطئة";
            qa.AnswerEN = "Wrong";
            if (rblChooseAnswer.SelectedValue == "0")
                qa.IsAnswer = true;
            else
                qa.IsAnswer = false;

            lstQuestionsAnswersReaded.Add(qa);

            numberOfAnswersReaded++;
            numberOfIsAnsweredReaded++;
            qa = new QuestionsAnswers();
            qa.AnswerAR = "عبارة صحيحة";
            qa.AnswerEN = "Right";
            qa.IsAnswer = !lstQuestionsAnswersReaded[0].IsAnswer;
                        

            lstQuestionsAnswersReaded.Add(qa);

        }
        


    }



    /// <summary>
    /// this function for clearing controls
    /// </summary>
    protected void clearAllControls()
    {
        txtQuestionEN.Text = "";
        txtQuestionAR.Text = "";
        ddlQuestionTypesID.SelectedValue = "1";
        ddlQuestionTypesID_SelectedIndexChanged(this, new EventArgs());
        txtQuestionDegree.Text = "5";
           
        txtAnswera.Text = "";
        txtAnsweraEN.Text = "";
        chkAnswera.Checked = false;
        txtAnswerb.Text = "";
        txtAnswerbEN.Text = "";
        chkAnswerb.Checked = false;
        txtAnswerc.Text = "";
        txtAnswercEN.Text = "";
        chkAnswerc.Checked = false;
        txtAnswerd.Text = "";
        txtAnswerdEN.Text = "";
        chkAnswerd.Checked = false;
        



        mObjQuestions = new Questions();

        mQuestionsID = -1;

        




    }



    /// <summary>
    /// this function for loading the editing behavior
    /// </summary>
    protected void editLoad()
    {


        Persons currentPerson = GlobalVars.getCurrentPerson();
               

        checkSecurityAndCustomizePage(currentPerson);

        checkID();


        BindAllControls();




        
    }



    /// <summary>
    /// this function will Save the question
    /// </summary>
    protected void Save()
    {
        
        QuestionsAnswersDB objQuestionsAnswersDB = new QuestionsAnswersDB(ConnectionStrings.LMS);

        if (checkForRepeats())
        {
            QuestionsDB objQuestionsDB = new QuestionsDB(ConnectionStrings.LMS);
            if (mObjQuestions.ID == -1)
            {
                ClassDataHandler con = new ClassDataHandler(ConnectionStrings.LMS);
                con.OpenTransConnection(System.Data.IsolationLevel.ReadUncommitted);
                try
                {
                    objQuestionsDB.Insert(con, mObjQuestions);
                    for (int i = 0; i < lstQuestionsAnswersReaded.Count; i++)
                    {
                        lstQuestionsAnswersReaded[i].QuestionsID = mObjQuestions.ID;
                        
                        objQuestionsAnswersDB.Insert(con, lstQuestionsAnswersReaded[i]);

                    }

                    con.CommitTransConnection();
                    mObjQuestions.clearRelations();

                }
                catch
                {
                    con.RollbackTransConnection();
                    lblError.Text = "Error saving question,try again later.";
                    return;
                }

                clearAllControls();
                bindGrid(txtSearch.Text);
                lblResult.Text = "Data saved ok.";
            }
            else
            {
                List<QuestionsAnswers> lstOldQuestions = mObjQuestions.lstQuestionsAnswers;

                ClassDataHandler con = new ClassDataHandler(ConnectionStrings.LMS);
                con.OpenTransConnection(System.Data.IsolationLevel.ReadUncommitted);

                try
                {
                    for (int i = 0; i < lstOldQuestions.Count; i++)
                    {

                        objQuestionsAnswersDB.Delete(con, lstOldQuestions[i]);

                    }
                    objQuestionsDB.Update(con,mObjQuestions);

                    for (int i = 0; i < lstQuestionsAnswersReaded.Count; i++)
                    {
                        lstQuestionsAnswersReaded[i].QuestionsID = mObjQuestions.ID;

                        objQuestionsAnswersDB.Insert(con, lstQuestionsAnswersReaded[i]);
                    }



                    con.CommitTransConnection();
                    mObjQuestions.clearRelations();

                }
                catch
                {
                    con.RollbackTransConnection();
                    lblError.Text = "Error saving question,try again later.";
                    return;
                }

                
                bindGrid(txtSearch.Text);
                BindAllControls();
                lblResult.Text = "Data saved ok.";

            }



        }


    }


    /// <summary>
    /// this function will check if the question exist with the same Name or not
    /// </summary>
    /// <returns>true if ok , false for error (question exist before)</returns>
    protected bool checkForRepeats()
    {
        QuestionsDB objQuestionsDB = new QuestionsDB(ConnectionStrings.LMS);
        List<Questions> lstRet = objQuestionsDB.Select(" top 1 ", " where ([CoursesID]='" + mObjQuestions.CoursesID + "')" + 
            " and ([QuestionAR]='" + mObjQuestions.QuestionAR.Replace("'","''") + "' " + 
            " or [QuestionEN]='"+ mObjQuestions.QuestionEN.Replace("'","''") +"') " + 
            " and ([ID] <> '" + mObjQuestions.ID + "') ");

        if (lstRet.Count > 0)
        {
            errorExist();
            return false;
        }


        return true;

    }




    /// <summary>
    /// this function will show a message with the error for existense
    /// </summary>
    private void errorExist()
    {

        lblError.Text = "Error , a Question with the same text and course  is already found , choose a new text";

    }



    protected void btnSave_Click(object sender, EventArgs e)
    {

        //security check
        Persons currentPerson = GlobalVars.getCurrentPerson();
        if (!currentPerson.lstAllRulesIDs.Contains((long)RulesEnum.Editing_questions_of_courses_page))
            return;


        if (Page.IsValid)
        {



            ReadAllControls();

            if (numberOfAnswersReaded < 2)
            {
                lblError.Text = "You must specify at least two answers";
                return;
            }

            if (numberOfIsAnsweredReaded == 0)
            {
                lblError.Text = "You must specify the right answer";
                return;
            }

            if (numberOfIsAnsweredReaded == numberOfAnswersReaded)
            {
                lblError.Text = "the right answers cannot be all answers";
                return;
            }



            Save();


        }
    }




    protected void btnDelete_Click(object sender, EventArgs e)
    {

        Persons objCurrentPersons = GlobalVars.getCurrentPerson();
        checkSecurityAndCustomizePage(objCurrentPersons);

        //security check

        if (!objCurrentPersons.lstAllRulesIDs.Contains((long)RulesEnum.Editing_questions_of_courses_page))
        {
            lblError.Text = "Security error , you can view only";
            lblResult.Text = "";

            return;
        }


        long QuestionsID = mQuestionsID;



        QuestionsDB objQuestionsDB = new QuestionsDB(ConnectionStrings.LMS);
        List<Questions> lstQuestions = objQuestionsDB.getQuestionsByID(QuestionsID);




        if (lstQuestions.Count == 0)
        {
            lblError.Text = "No Questions to delete";
            lblResult.Text = "";
            return;
        }





        //if (lstQuestions[0].lstTickets.Count > 0)
        //{

        //    lblError.Text = "Error Deleting this type , there is tickets witch uses it";

        //    return;
        //}



        List<QuestionsAnswers> lstQuestionsAnswers = lstQuestions[0].lstQuestionsAnswers;

        ClassDataHandler con = new ClassDataHandler(ConnectionStrings.LMS);
        con.OpenTransConnection(System.Data.IsolationLevel.ReadUncommitted);

        try
        {

            for (int i = 0; i < lstQuestionsAnswers.Count; i++)
            {
                QuestionsAnswersDB objQuestionsAnswers = new QuestionsAnswersDB();
                objQuestionsAnswers.Delete(con, lstQuestionsAnswers[i]);
            }


            objQuestionsDB.Delete(con, lstQuestions[0]);

            con.CommitTransConnection();

        }
        catch
        {
            con.RollbackTransConnection();
            lblError.Text = "Error deleting questions.";
            return;
        }



        lblResult.Text = "Deleted ok.";
        bindGrid(txtSearch.Text);
        clearAllControls();
        
        return;



        

        






    }




    protected void grdUsers_RowEditing(object sender, GridViewEditEventArgs e)
    {
        Persons objCurrentPersons = GlobalVars.getCurrentPerson();
        checkSecurityAndCustomizePage(objCurrentPersons);



        long QuestionsID = long.Parse(grdUsers.DataKeys[e.NewEditIndex]["ID"].ToString());

        mQuestionsID = QuestionsID;

        editLoad();

        e.Cancel = true;

    }



    protected void ddlQuestionTypesID_SelectedIndexChanged(object sender, EventArgs e)
    {
        if (ddlQuestionTypesID.SelectedValue == "1")
        {
            pnlChoose.Visible = true;
            pnlRightWrong.Visible = false;

        }
        else
        {
            pnlChoose.Visible = false;
            pnlRightWrong.Visible = true;
        }

    }
}
